package com.atguigu.day03;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class Flink05_Transform_KeyBy {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(4);

        //2.从端口读取数据
        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);


        //3.使用map将从端口读进来的字符串转为JavaBean
        SingleOutputStreamOperator<WaterSensor> map = streamSource.map(new MapFunction<String, WaterSensor>() {

            @Override
            public WaterSensor map(String value) throws Exception {
                String[] split = value.split(" ");
                return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
            }
        }).setParallelism(2);

        //TODO 4.使用keyby将相同id的数据聚和到一块
        //第一种方式：使用匿名实现类实现key的选择器
      /*  KeyedStream<WaterSensor, String> keyedStream = map.keyBy(new KeySelector<WaterSensor, String>() {
            @Override
            public String getKey(WaterSensor value) throws Exception {
                return value.getId();
            }
        });
*/
        //第二种方式:定一个类实现KeySelector接口指定key
//        KeyedStream<WaterSensor, String> keyedStream = map.keyBy(new MyKey());

        //第三种方式:lambda表达式
//        KeyedStream<WaterSensor, String> keyedStream = map.keyBy(r -> r.getId());

//        KeyedStream<WaterSensor, String> keyedStream = map.keyBy(WaterSensor::getId);

        //第四中方式：通过属性名获取key 常用于pojo
        KeyedStream<WaterSensor, Tuple> keyedStream = map.keyBy("id");

        map.print("原始数据").setParallelism(2);
        keyedStream.print("keyby");

        env.execute();
    }
    public static class MyKey implements KeySelector<WaterSensor,String>{

        @Override
        public String getKey(WaterSensor value) throws Exception {
            return value.getId();
        }
    }

}
